<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\logic;

/**
 * 会员逻辑
 */
class Member extends LogicBase
{
    /**
     * 获取会员列表搜索条件
     */
    public function getWhere($data = [])
    {
        $where = [];
        
        // 搜索条件：昵称、用户名、邮箱、手机号
        !empty($data['search_data']) && $where['m.nickname|m.username|m.email|m.mobile'] = ['like', '%'.$data['search_data'].'%'];
        
        // 权限控制：非管理员只能查看自己的下级
        if (!is_administrator()) {
            $member = session('member_info');
            
            if ($member['is_share_member']) {
                // 共享会员可以查看继承的会员
                $ids = $this->getInheritMemberIds(MEMBER_ID);
                $ids[] = MEMBER_ID;
                $where['m.leader_id'] = ['in', $ids];
            } else {
                // 普通会员只能查看直接下级
                $where['m.leader_id'] = MEMBER_ID;
            }
        }
        
        return $where;
    }
    
    /**
     * 获取存在继承关系的会员ids
     */
    public function getInheritMemberIds($id = 0, $data = [])
    {
        $member_id = $this->modelMember->getValue(['id' => $id, 'is_share_member' => DATA_NORMAL], 'leader_id');
        
        if (empty($member_id)) {
            return $data;
        }
        
        $data[] = $member_id;
        
        return $this->getInheritMemberIds($member_id, $data);
    }
    
    /**
     * 获取会员信息
     */
    public function getMemberInfo($where = [], $field = true)
    {
        
        return $this->modelMember->getInfo($where, $field);
    }
    
    /**
     * 获取会员套餐配置
     */
    public function getMemberPlans($data = [])
    {
        try {
            // 获取VIP套餐列表
            $where = ['status' => 1];
            $field = 'id, name, price, duration, description, benefits, sort';
        $order = 'sort ASC, id ASC';
            
            $list = $this->modelVipPackage->getList($where, $field, $order, false);
            
            if (empty($list)) {
                // 返回默认套餐配置
                $defaultPlans = [
                    [
                        'id' => 1,
                        'name' => '月度会员',
                        'price' => 29.9,
                        'duration' => 30,
                        'description' => '享受一个月的会员特权',
                        'benefits' => ['无限制查看行情', '专属客服', '优先推荐'],
                        'sort' => 1
                    ],
                    [
                        'id' => 2,
                        'name' => '季度会员',
                        'price' => 79.9,
                        'duration' => 90,
                        'description' => '享受三个月的会员特权',
                        'benefits' => ['无限制查看行情', '专属客服', '优先推荐', '专属标识'],
                        'sort' => 2
                    ],
                    [
                        'id' => 3,
                        'name' => '年度会员',
                        'price' => 299.9,
                        'duration' => 365,
                        'description' => '享受一年的会员特权',
                        'benefits' => ['无限制查看行情', '专属客服', '优先推荐', '专属标识', '专属活动'],
                        'sort' => 3
                    ]
                ];
                
                return [RESULT_SUCCESS, '获取成功', $defaultPlans];
            }
            
            return [RESULT_SUCCESS, '获取成功', $list];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取会员套餐失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取最近充值会员列表
     */
    public function getRecentMembers($data = [])
    {
        try {
            $limit = $data['limit'] ?? 10;
            
            // 获取最近的VIP订单
            $where = ['status' => 1, 'pay_status' => 1]; // 已支付的订单
            $field = 'user_id, package_name, create_time';
            $order = 'create_time DESC';
            $paginate = ['list_rows' => $limit];
            
            $list = $this->modelVipOrder->getList($where, $field, $order, $paginate);
            
            if (empty($list)) {
                // 返回默认数据
                $defaultMembers = [
                    ['user_id' => 1001, 'package_name' => '年度会员', 'create_time' => time() - 3600],
                    ['user_id' => 1002, 'package_name' => '季度会员', 'create_time' => time() - 7200],
                    ['user_id' => 1003, 'package_name' => '月度会员', 'create_time' => time() - 10800],
                    ['user_id' => 1004, 'package_name' => '年度会员', 'create_time' => time() - 14400],
                    ['user_id' => 1005, 'package_name' => '季度会员', 'create_time' => time() - 18000]
                ];
                
                return [RESULT_SUCCESS, '获取成功', $defaultMembers];
            }
            
            return [RESULT_SUCCESS, '获取成功', $list];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取最近会员失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 创建VIP订单
     */
    public function createVipOrder($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            $planId = $data['plan_id'] ?? 0;
            $price = $data['price'] ?? 0;
            $duration = $data['duration'] ?? 0;
            $paymentMethod = $data['payment_method'] ?? 'wechat';
            
            if (!$userId || !$planId || !$price) {
                return [RESULT_ERROR, '参数不完整'];
            }
            
            // 生成订单号
            $orderNo = 'VIP' . date('YmdHis') . rand(1000, 9999);
            
            // 创建订单
            $orderData = [
                'order_no' => $orderNo,
                'user_id' => $userId,
                'package_type' => $data['package_type'] ?? 'month',
                'package_name' => $data['package_name'] ?? '会员套餐',
                'amount' => $price,
                'payment_method' => $paymentMethod,
                'status' => 0, // 待支付
                'create_time' => time()
            ];
            
            $orderId = $this->modelVipOrder->updateInfo([], $orderData);
            
            if ($orderId) {
                return [RESULT_SUCCESS, '订单创建成功', ['order_id' => $orderId, 'order_no' => $orderNo]];
            } else {
                return [RESULT_ERROR, '订单创建失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '创建订单失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 发起支付请求
     */
    public function requestPayment($data = [])
    {
        try {
            $orderId = $data['order_id'] ?? '';
            $paymentMethod = $data['payment_method'] ?? 'wechat';
            
            if (!$orderId) {
                return [RESULT_ERROR, '订单ID不能为空'];
            }
            
            // 获取订单信息
            $order = $this->modelVipOrder->getInfo(['id' => $orderId]);
            
            if (empty($order)) {
                return [RESULT_ERROR, '订单不存在'];
            }
            
            if ($order['pay_status'] == 1) {
                return [RESULT_ERROR, '订单已支付'];
            }
            
            // 这里应该调用支付接口，暂时返回模拟数据
            $paymentData = [
                'payment_url' => 'https://example.com/pay/' . $order['order_no'],
                'qr_code' => '',
                'order_no' => $order['order_no'],
                'amount' => $order['price']
            ];
            
            return [RESULT_SUCCESS, '支付请求成功', $paymentData];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '发起支付失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取用户会员信息
     */
    public function getUserMemberInfo($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            // 获取用户VIP信息（从user表中获取）
            $userInfo = $this->modelUser->getInfo(['id' => $userId], 'vip_level,vip_expire_time');
            
            if (empty($userInfo)) {
                return [RESULT_ERROR, '用户不存在'];
            }
            
            // 计算剩余天数
            $expireTime = $userInfo['vip_expire_time'] ?? 0;
            $remainingDays = max(0, ceil(($expireTime - time()) / 86400));
            
            $memberInfo = [
                'is_vip' => $expireTime > time(),
                'vip_level' => $userInfo['vip_level'] ?? 0,
                'expire_time' => $expireTime,
                'remaining_days' => $remainingDays
            ];
            
            return [RESULT_SUCCESS, '获取成功', $memberInfo];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取会员信息失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取会员权益
     */
    public function getMemberBenefits($data = [])
    {
        try {
            // 返回会员权益列表
            $benefits = [
                [
                    'title' => '无限制查看行情',
                    'description' => '查看所有商品的实时行情和历史数据',
                    'icon' => 'chart'
                ],
                [
                    'title' => '专属客服',
                    'description' => '享受一对一专属客服服务',
                    'icon' => 'service'
                ],
                [
                    'title' => '优先推荐',
                    'description' => '优先获得热门商品推荐',
                    'icon' => 'star'
                ],
                [
                    'title' => '专属标识',
                    'description' => '显示专属会员标识',
                    'icon' => 'vip'
                ],
                [
                    'title' => '专属活动',
                    'description' => '参与会员专属活动和优惠',
                    'icon' => 'activity'
                ]
            ];
            
            return [RESULT_SUCCESS, '获取成功', $benefits];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取会员权益失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 验证会员状态
     */
    public function validateMemberStatus($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            // 获取用户VIP信息（从user表中获取）
            $userInfo = $this->modelUser->getInfo(['id' => $userId], 'vip_level,vip_expire_time');
            
            $isValid = false;
            $message = '非会员用户';
            
            if (!empty($userInfo)) {
                $expireTime = $userInfo['vip_expire_time'] ?? 0;
                if ($expireTime > time()) {
                    $isValid = true;
                    $message = '会员状态有效';
                } elseif ($expireTime > 0 && $expireTime <= time()) {
                    $message = '会员已过期';
                }
            }
            
            return [RESULT_SUCCESS, $message, ['is_valid' => $isValid]];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '验证会员状态失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取会员订单列表
     */
    public function getMemberOrders($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            $page = $data['page'] ?? 1;
            $limit = $data['limit'] ?? 20;
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            $where = ['user_id' => $userId];
            $field = 'id, order_no, package_name, price, status, pay_status, create_time';
            $order = 'create_time DESC';
            $paginate = ['list_rows' => $limit, 'page' => $page];
            
            $list = $this->modelVipOrder->getList($where, $field, $order, $paginate);
            
            return [RESULT_SUCCESS, '获取成功', $list];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取订单列表失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取订单详情
     */
    public function getOrderDetail($data = [])
    {
        try {
            $orderId = $data['order_id'] ?? 0;
            $userId = $data['user_id'] ?? 0;
            
            if (!$orderId || !$userId) {
                return [RESULT_ERROR, '参数不完整'];
            }
            
            $where = ['id' => $orderId, 'user_id' => $userId];
            $order = $this->modelVipOrder->getInfo($where);
            
            if (empty($order)) {
                return [RESULT_ERROR, '订单不存在'];
            }
            
            return [RESULT_SUCCESS, '获取成功', $order];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取订单详情失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 取消订单
     */
    public function cancelOrder($data = [])
    {
        try {
            $orderId = $data['order_id'] ?? 0;
            $userId = $data['user_id'] ?? 0;
            
            if (!$orderId || !$userId) {
                return [RESULT_ERROR, '参数不完整'];
            }
            
            // 获取订单信息
            $order = $this->modelVipOrder->getInfo(['id' => $orderId, 'user_id' => $userId]);
            
            if (empty($order)) {
                return [RESULT_ERROR, '订单不存在'];
            }
            
            if ($order['pay_status'] == 1) {
                return [RESULT_ERROR, '已支付订单无法取消'];
            }
            
            if ($order['status'] == 2) {
                return [RESULT_ERROR, '订单已取消'];
            }
            
            // 更新订单状态为已取消
            $result = $this->modelVipOrder->updateInfo(['id' => $orderId], ['status' => 2]);
            
            if ($result) {
                return [RESULT_SUCCESS, '订单取消成功'];
            } else {
                return [RESULT_ERROR, '订单取消失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '取消订单失败：' . $e->getMessage()];
        }
    }
}
